<?php

namespace app\store\controller;

use app\common\library\helper;
use think\Cache;
use app\store\model\Goods;
use app\store\model\Order;
use app\store\model\User;
use think\Log;

/**
 * 后台首页
 * Class Index
 * @package app\store\controller
 */
class Index extends Controller
{
    public function index()
    {
        $today = date('Y-m-d');
        $startTime = strtotime($today.' 00:00:00');
        $endTime = strtotime($today. '23:59:59');
        $todayTime = [$startTime, $endTime];

        //商城统计
        $agentCounts = $this->agentCounts();
        $total = [
            'pay_price' => Order::where(['pay_status' => 20])->sum('pay_price'),
            'pay_orders' => Order::where(['pay_status' => 20])->count(),
            'agent_total' => $agentCounts['total'],
            'agent_counts' => $agentCounts['counts'],
            'yesterdayNewUser' => $this->yesterdayNewUser($todayTime),
            'yesterdayOrderCount'=> $this->yesterdayOrderCount($todayTime),
            'yesterdayTotalPay' => $this->yesterdayTotalPay($todayTime),
            'noPayOrderCount' => $this->noPayOrderCount()
        ];
        return $this->fetch('index', compact('total'));
    }

    private function agentCounts()
    {
        $agents = helper::getAgents();
        $rows = User::field('agent_level,count(1) as total')->group("agent_level")->select();
        $counts = [];
        foreach ($rows as $row) {
            $counts[$row->agent_level] = $row->total;
        }
        $total = 0;
        foreach ($agents as $level => &$agent) {
            if (isset($counts[$level])) {
                $agent['total'] = $counts[$level];
                $total += $counts[$level];
            } else {
                $agent['total'] = 0;
            }
        }
        return ['counts' => $agents, 'total' => $total];
    }

    private function yesterdayNewUser($todayTime)
    {
        return User::where(['create_time'=>['between',$todayTime]])->count();
    }

    private function yesterdayOrderCount(array $todayTime)
    {
        return Order::where(['pay_status' => 20, 'create_time'=>['between',$todayTime]])->count();
    }

    private function yesterdayTotalPay(array $todayTime)
    {
        return Order::where(['pay_status' => 20, 'create_time'=>['between',$todayTime]])->sum("pay_price");
    }

    private function noPayOrderCount()
    {
        return Order::where(['pay_status' => 10])->count();
    }


}
